<template>
  <div class="work-fixture-page">
    <div class="hero-card">
      <div class="hero-content">
        <div class="hero-title">
          <div class="hero-icon">
            <el-icon><Collection /></el-icon>
          </div>
          <div>
            <p class="hero-subtitle">工具管理 · 工装夹具档案</p>
            <h2>工装夹具档案列表</h2>
            <div class="hero-tags">
              <el-tag effect="dark" size="small" type="success">实时</el-tag>
              <el-tag effect="plain" size="small" type="primary"
                >支持批量</el-tag
              >
              <el-tag effect="plain" size="small" type="info">可视化</el-tag>
            </div>
          </div>
        </div>
        <div class="hero-meta">
          <div class="meta-item">
            <span class="meta-label">总档案</span>
            <strong>{{ stateStatistics.total }}</strong>
          </div>
          <div class="meta-item">
            <span class="meta-label">在库</span>
            <strong>{{ stateStatistics.inStock }}</strong>
          </div>
          <div class="meta-item">
            <span class="meta-label">被领用</span>
            <strong>{{ stateStatistics.borrowed }}</strong>
          </div>
          <div class="meta-item warning">
            <span class="meta-label">预警>0</span>
            <strong>{{ stateStatistics.warning }}</strong>
          </div>
        </div>
      </div>
      <el-breadcrumb :separator-icon="ArrowRight" class="hero-breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>工具管理</el-breadcrumb-item>
        <el-breadcrumb-item>工装夹具档案</el-breadcrumb-item>
        <el-breadcrumb-item>列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card shadow="never" class="search-card" style="margin-top: 5px">
      <template #header>
        <div class="card-header">
          <div class="card-title">
            <el-icon><Search /></el-icon>
            <span>智能过滤</span>
          </div>
          <el-button link type="primary" size="small" @click="handleRefresh">
            刷新列表
          </el-button>
        </div>
      </template>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入工装夹具编码/名称"
            clearable
            style="width: 240px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.work_fixturetypeid"
            placeholder="请选择工装夹具类型"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in work_fixturetypelist"
              :key="item.id"
              :label="item.work_fixturetypename"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.state"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" :loading="loading" @click="handleSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card" style="margin-top: 5px">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            @click="flowAdd"
            class="toolbar-btn-primary"
          >
            <el-icon><Tickets /></el-icon>
            新增档案
          </el-button>
          <el-button
            type="danger"
            plain
            @click="handleBatchDelete"
            class="toolbar-btn-danger"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-tag size="small" effect="plain">
            已选择 {{ multipleSelection.length }} 项
          </el-tag>
          <el-divider direction="vertical" />
          <el-button size="small" link @click="handleExport">
            导出视图
          </el-button>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        class="modern-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="编号" width="80" align="center">
          <template #default="scope">
            <span class="table-id">{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="work_fixturecode"
          label="工装夹具编码"
          min-width="180"
        >
          <template #default="scope">
            <div class="table-code">
              <el-icon class="code-icon"><Tickets /></el-icon>
              <span>{{ scope.row.work_fixturecode }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="work_fixturename"
          label="工装夹具名称"
          min-width="160"
        >
          <template #default="scope">
            <span class="table-name">{{ scope.row.work_fixturename }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="work_fixturetypename"
          label="工装夹具类型"
          min-width="140"
        >
          <template #default="scope">
            <el-tag size="small" effect="plain" type="info">
              {{ scope.row.work_fixturetypename }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="work_fixturemodels" label="型号" min-width="120">
          <template #default="scope">
            <span class="table-model">{{ scope.row.work_fixturemodels }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="work_fixtureseatname"
          label="存放库位"
          min-width="140"
        >
          <template #default="scope">
            <div class="table-seat">
              <el-icon class="seat-icon"><OfficeBuilding /></el-icon>
              <span>{{ scope.row.work_fixtureseatname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="early_warningnum"
          label="预警次数"
          width="110"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="
                Number(scope.row.early_warningnum) > 0 ? 'warning' : 'success'
              "
              size="small"
              effect="dark"
            >
              {{ scope.row.early_warningnum || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span class="table-remark">{{ scope.row.remark || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.state == 0 ? 'success' : 'danger'"
              effect="dark"
              size="small"
            >
              {{ scope.row.state == 0 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                circle
                @click="flowUpdate(scope.row)"
                title="编辑"
              />
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                circle
                @click="open(scope.row.id)"
                title="删除"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <div class="pagination-wrapper">
          <div class="pagination-info">
            <span class="pagination-text">
              共 <strong>{{ info.totalCount }}</strong> 条记录，每页显示
            </span>
            <el-select
              v-model="info.PageSize"
              size="small"
              style="width: 80px; margin: 0 8px"
              @change="handleSizeChange"
            >
              <el-option :value="2" label="2" />
              <el-option :value="10" label="10" />
              <el-option :value="15" label="15" />
              <el-option :value="20" label="20" />
            </el-select>
            <span class="pagination-text">条</span>
          </div>
          <div class="pagination-controls">
            <el-button
              size="small"
              :icon="ArrowLeft"
              @click="gotoFirst"
              :disabled="info.Pageindex === 1"
              circle
            />
            <el-button
              size="small"
              @click="gotoPrev"
              :disabled="info.Pageindex === 1"
              >上一页</el-button
            >
            <el-pagination
              v-model:current-page="info.Pageindex"
              :page-size="info.PageSize"
              :page-sizes="[2, 10, 15, 20]"
              background
              layout="prev, pager, next"
              :total="info.totalCount"
              @current-change="handleCurrentChange"
              small
            />
            <el-button
              size="small"
              @click="gotoNext"
              :disabled="info.Pageindex >= totalPages"
              >下一页</el-button
            >
            <el-button
              size="small"
              :icon="ArrowRight"
              @click="gotoLast"
              :disabled="info.Pageindex >= totalPages"
              circle
            />
          </div>
        </div>
      </div>
    </el-card>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="title" width="1500px">
    <template #header>
      <div class="fixture-dialog-header">
        <div>
          <p class="fixture-dialog-subtitle">工具管理 · 工装夹具档案</p>
          <h3 class="fixture-dialog-title">{{ title }}</h3>
        </div>
        <el-tag :type="isAutoCode ? 'success' : 'info'" effect="dark">
          {{ isAutoCode ? "自动编码" : "手动录入" }}
        </el-tag>
      </div>
    </template>
    <div class="fixture-dialog-body">
      <div class="fixture-summary-panel">
        <div class="summary-content">
          <el-icon class="summary-icon"><Tickets /></el-icon>
          <div>
            <p class="summary-label">当前编号</p>
            <h4 class="summary-value">
              {{ ruleForm.work_fixturecode || "待填写" }}
            </h4>
          </div>
        </div>
        <div class="summary-tags">
          <el-tag :type="autoCodeStatusType" effect="plain">
            {{ autoCodeStatusText }}
          </el-tag>
          <el-tag type="warning" effect="plain">必填项已配置校验</el-tag>
        </div>
      </div>
      <div class="fixture-layout">
        <el-scrollbar
          class="fixture-scroll fixture-layout__form"
          height="430px"
        >
          <div class="fixture-form">
            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="110px"
            >
              <div class="fixture-section-grid">
                <div class="fixture-section fixture-section--wide">
                  <div class="fixture-section__title">
                    <el-icon><Tickets /></el-icon>
                    <span>基础信息</span>
                  </div>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label="工装夹具编号"
                        prop="work_fixturecode"
                      >
                        <div class="code-input">
                          <el-input
                            v-model="ruleForm.work_fixturecode"
                            :disabled="isAutoCode"
                            placeholder="请输入工装夹具编号"
                          />
                          <el-switch
                            v-model="isAutoCode"
                            inline-prompt
                            active-text="系统编码"
                            inactive-text="手动输入"
                            @change="handleAutoCodeChange"
                          />
                          <span class="code-switch-label">开启后自动生成</span>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="工装夹具名称"
                        prop="work_fixturename"
                      >
                        <el-input v-model="ruleForm.work_fixturename" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label="工装夹具类型"
                        prop="work_fixturetypeid"
                      >
                        <el-select
                          v-model="ruleForm.work_fixturetypeid"
                          placeholder="请选择类型"
                          style="width: 100%"
                        >
                          <el-option
                            v-for="item in warehouselist"
                            :key="item.id"
                            :label="item.work_fixturetypename"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="工装夹具型号"
                        prop="work_fixturemodels"
                      >
                        <el-input v-model="ruleForm.work_fixturemodels" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>

                <div class="fixture-section">
                  <div class="fixture-section__title">
                    <el-icon><OfficeBuilding /></el-icon>
                    <span>存放信息</span>
                  </div>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label="存放库位"
                        prop="work_fixtureseatid"
                        style="width: 220px"
                      >
                        <el-select
                          v-model="ruleForm.work_fixtureseatid"
                          placeholder="请选择存放库位"
                          style="width: 100%"
                        >
                          <el-option
                            v-for="item in Reservoirlist"
                            :key="item.id"
                            :label="item.work_fixtureseatname"
                            :value="item.id"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="预警次数" prop="early_warningnum">
                        <el-input
                          v-model.number="ruleForm.early_warningnum"
                          type="number"
                          placeholder="请输入预警次数"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>

                <div class="fixture-section">
                  <div class="fixture-section__title">
                    <el-icon><Setting /></el-icon>
                    <span>状态配置</span>
                  </div>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="状态" prop="state">
                        <el-radio-group v-model="ruleForm.state">
                          <el-radio :value="0">在库</el-radio>
                          <el-radio :value="1">被领用</el-radio>
                          <el-radio :value="2">报废</el-radio>
                          <el-radio :value="3">维修中</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>

                <div class="fixture-section fixture-section--wide">
                  <div class="fixture-section__title">
                    <el-icon><InfoFilled /></el-icon>
                    <span>备注信息</span>
                  </div>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="备注" prop="remark">
                        <el-input
                          v-model="ruleForm.remark"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入备注"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-form>
          </div>
        </el-scrollbar>
        <div class="fixture-layout__side">
          <div class="fixture-side-card preview-card">
            <div class="preview-card__header">
              <h4>录入概览</h4>
              <el-tag :type="statePreview.type" effect="dark">
                {{ statePreview.text }}
              </el-tag>
            </div>
            <el-descriptions
              :column="1"
              size="small"
              class="preview-descriptions"
            >
              <el-descriptions-item label="夹具类型">
                {{ selectedTypeName }}
              </el-descriptions-item>
              <el-descriptions-item label="存放库位">
                {{ selectedSeatName }}
              </el-descriptions-item>
              <el-descriptions-item label="预警次数">
                {{ warningTimesText }}
              </el-descriptions-item>
            </el-descriptions>
            <el-divider content-position="left">关键字段</el-divider>
            <div class="preview-chips">
              <el-tag size="small" type="info">{{ selectedTypeName }}</el-tag>
              <el-tag size="small" type="success">{{
                selectedSeatName
              }}</el-tag>
              <el-tag size="small" type="warning">{{
                warningTimesText
              }}</el-tag>
            </div>
          </div>
          <div class="fixture-side-card progress-card">
            <div class="progress-card__header">
              <h4>填写进度</h4>
              <span>{{ formProgress.percent }}%</span>
            </div>
            <el-progress
              :percentage="formProgress.percent"
              :status="progressStatus"
              :color="progressBarColor"
              :stroke-width="12"
            />
            <p class="progress-card__text">
              已完成 {{ formProgress.filled }}/{{ formProgress.total }}
              项必填信息
            </p>
            <div class="progress-tips">
              <el-icon><BellFilled /></el-icon>
              <span>推荐开启系统编码快速完成编号输入</span>
            </div>
          </div>
          <div class="fixture-side-card tips-card">
            <div class="tips-card__header">
              <h4>填写提示</h4>
              <el-tag effect="plain" size="small" type="info">Tips</el-tag>
            </div>
            <ul class="tips-list">
              <li v-for="tip in helperTips" :key="tip.title">
                <div class="tips-list__title">{{ tip.title }}</div>
                <p>{{ tip.desc }}</p>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="success" @click="submitForm(ruleFormRef)"
          >保存</el-button
        >
        <el-button type="primary" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="warning" @click="resetForm(ruleFormRef)"
          >重置</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  ArrowLeft,
  ArrowRight,
  BellFilled,
  Collection,
  Delete,
  Edit,
  InfoFilled,
  OfficeBuilding,
  Search,
  Setting,
  Tickets,
} from "@element-plus/icons-vue";
import https from "@/Http/http";
import axios from "axios";
import { onMounted, reactive, ref, computed, watch } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { ElMessageBox } from "element-plus";
import router from "@/router";

onMounted(() => {
  work_fixtureShow();
  warehouseshow();
  Reservoirshow();
  work_fixturetypeshow();
});
const tableData = ref([]);
const loading = ref(false);
const info = reactive({
  Pageindex: 1,
  PageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const searchForm = reactive({
  keyword: "",
  work_fixturetypeid: "",
  state: "",
});

const statusOptions = [
  { label: "启用", value: 0 },
  { label: "禁用", value: 1 },
];

const stateStatistics = computed(() => {
  const total = info.totalCount || tableData.value.length;
  const counts = tableData.value.reduce(
    (acc, cur: any) => {
      if (cur.state === 0) acc.inStock += 1;
      if (cur.state === 1) acc.borrowed += 1;
      if (Number(cur.early_warningnum) > 0) acc.warning += 1;
      return acc;
    },
    { inStock: 0, borrowed: 0, warning: 0 }
  );
  return {
    total,
    ...counts,
  };
});

const work_fixtureShow = () => {
  loading.value = true;
  const params: any = {
    Pageindex: info.Pageindex,
    PageSize: info.PageSize,
    Work_fixturecode: searchForm.keyword || undefined,
    Work_fixturename: searchForm.keyword || undefined,
    Work_fixturetypeid: searchForm.work_fixturetypeid || undefined,
    State: searchForm.state !== "" ? searchForm.state : undefined,
  };
  https.Reads.get("/Applicae/work_fixturelist", {
    params,
  })
    .then((res) => {
      console.log(res.data);
      tableData.value = res.data.data;
      info.totalCount = res.data.totalCount;
      info.pageCount = res.data.pageCount;
    })
    .catch((error) => {
      ElMessage.error("获取工装夹具列表失败，请稍后重试");
      tableData.value = [];
      info.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleSearch = () => {
  info.Pageindex = 1;
  work_fixtureShow();
};

const handleReset = () => {
  searchForm.keyword = "";
  searchForm.work_fixturetypeid = "";
  searchForm.state = "";
  handleSearch();
};

const handleRefresh = () => {
  ElMessage.success("刷新成功");
  work_fixtureShow();
};

const handleExport = () => {
  ElMessage.info("导出功能暂未开放，敬请期待");
};

const handleSizeChange = (val: number) => {
  info.PageSize = val;
  info.Pageindex = 1;
  work_fixtureShow();
};
const handleCurrentChange = (val: number) => {
  info.Pageindex = val;
  work_fixtureShow();
};

const totalPages = computed(() =>
  Math.max(1, Math.ceil(info.totalCount / info.PageSize))
);
const gotoFirst = () => {
  if (info.Pageindex !== 1) {
    info.Pageindex = 1;
    work_fixtureShow();
  }
};
const gotoPrev = () => {
  if (info.Pageindex > 1) {
    info.Pageindex -= 1;
    work_fixtureShow();
  }
};
const gotoNext = () => {
  if (info.Pageindex < totalPages.value) {
    info.Pageindex += 1;
    work_fixtureShow();
  }
};
const gotoLast = () => {
  if (info.Pageindex !== totalPages.value) {
    info.Pageindex = totalPages.value;
    work_fixtureShow();
  }
};

type RuleForm = {
  id: number;
  work_fixturecode: string;
  work_fixturename: string;
  work_fixturetypeid: number | string;
  work_fixturemodels: string;
  work_fixtureseatid: number | string | null;
  early_warningnum: number | null;
  remark: string;
  state: number | null;
};

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  id: 0,
  work_fixturecode: "",
  work_fixturename: "",
  work_fixturetypeid: "",
  work_fixturemodels: "",
  work_fixtureseatid: null,
  early_warningnum: null,
  remark: "",
  state: null,
});
const isAutoCode = ref(false);
const manualCodeCache = ref("");
const autoCodeStatusText = computed(() =>
  isAutoCode.value ? "系统自动编号已开启" : "手动输入模式"
);
const autoCodeStatusType = computed(() =>
  isAutoCode.value ? "success" : "info"
);
const dialogFormVisible = ref(false);
const title = ref();
const multipleSelection = ref<any[]>([]);
const helperTips = [
  {
    title: "编码规范",
    desc: "系统自动编码基于时间戳生成，确保唯一并方便追溯。",
  },
  {
    title: "库位联动",
    desc: "优先选择与夹具类型匹配的库位，方便后续领用及盘点。",
  },
  {
    title: "状态同步",
    desc: "若夹具处于维修或报废，请及时更新状态以便预警准确。",
  },
];

const requiredFieldKeys: (keyof RuleForm)[] = [
  "work_fixturecode",
  "work_fixturename",
  "work_fixturetypeid",
  "work_fixturemodels",
  "work_fixtureseatid",
  "early_warningnum",
  "state",
  "remark",
];

const formProgress = computed(() => {
  const total = requiredFieldKeys.length;
  const filled = requiredFieldKeys.filter((key) => {
    const value = ruleForm[key];
    return value !== "" && value !== null && value !== undefined;
  }).length;
  const percent = Math.round((filled / total) * 100);
  return {
    total,
    filled,
    percent: Number.isFinite(percent) ? percent : 0,
  };
});

const progressStatus = computed<
  "success" | "warning" | "exception" | undefined
>(() => {
  if (formProgress.value.percent === 100) return "success";
  if (formProgress.value.percent < 50) return "warning";
  return undefined;
});

const progressBarColor = computed(() => {
  if (formProgress.value.percent === 100) {
    return "#67C23A";
  }
  if (formProgress.value.percent >= 50) {
    return "#409EFF";
  }
  return "#E6A23C";
});

const stateDictionary = [
  { value: 0, text: "在库", type: "success" },
  { value: 1, text: "被领用", type: "warning" },
  { value: 2, text: "报废", type: "danger" },
  { value: 3, text: "维修中", type: "info" },
];

const statePreview = computed(() => {
  const target = stateDictionary.find((item) => item.value === ruleForm.state);
  return (
    target || {
      text: "待设置状态",
      type: "info",
    }
  );
});

const warningTimesText = computed(() => {
  const value = ruleForm.early_warningnum;
  if (value === null || Number.isNaN(value)) {
    return "未设置";
  }
  return `${value} 次`;
});
//打开弹框
const flowAdd = () => {
  if ((title.value = "工装夹具信息新增")) {
    dialogFormVisible.value = true;
    isAutoCode.value = true;
    manualCodeCache.value = "";
    ruleForm.id = 0;
    ruleForm.work_fixturecode = "";
    ruleForm.work_fixturename = "";
    ruleForm.work_fixturetypeid = "";
    ruleForm.work_fixturemodels = "";
    ruleForm.work_fixtureseatid = null;
    ruleForm.early_warningnum = null;
    ruleForm.state = null;
    ruleForm.remark = "";
    if (isAutoCode.value) {
      ruleForm.work_fixturecode = generateWorkFixtureCode();
    }
  }
};
const flowUpdate = (row: any) => {
  if ((title.value = "工装夹具信息编辑")) {
    Object.assign(ruleForm, row);
    isAutoCode.value = false;
    manualCodeCache.value = row.work_fixturecode || "";
    dialogFormVisible.value = true;
  }
};

// 自动生成工装夹具编号（按 年月日时分秒，确保每次不同）
const generateWorkFixtureCode = () => {
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, "0");
  const year = now.getFullYear().toString();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hour = pad(now.getHours());
  const minute = pad(now.getMinutes());
  const second = pad(now.getSeconds());
  const millisecond = now.getMilliseconds().toString().padStart(3, "0");
  const random = Math.floor(Math.random() * 900 + 100); // 100-999
  return `GZJJBH${year}${month}${day}${hour}${minute}${second}${millisecond}${random}`;
};

// 切换系统编码开关时的处理
const handleAutoCodeChange = (value: boolean) => {
  if (value) {
    manualCodeCache.value = ruleForm.work_fixturecode || "";
    ruleForm.work_fixturecode = generateWorkFixtureCode();
  } else {
    ruleForm.work_fixturecode = manualCodeCache.value || "";
  }
};

watch(
  () => ruleForm.work_fixturecode,
  (val) => {
    if (!isAutoCode.value) {
      manualCodeCache.value = val || "";
    }
  }
);

const rules = reactive<FormRules>({
  work_fixturecode: [
    { required: true, message: "工装夹具编码不可为空", trigger: "blur" },
  ],
  work_fixturename: [
    { required: true, message: "工装夹具名称不可为空", trigger: "blur" },
  ],
  work_fixturetypeid: [
    { required: true, message: "工装夹具类型不可为空", trigger: "blur" },
  ],
  work_fixturemodels: [
    { required: true, message: "工装夹具型号不可为空", trigger: "blur" },
  ],
  work_fixtureseatid: [
    { required: true, message: "存放库位不可为空", trigger: "blur" },
  ],
  early_warningnum: [
    { required: true, message: "预警次数不可为空", trigger: "blur" },
  ],
  state: [{ required: true, message: "状态不可为空", trigger: "blur" }],
  remark: [{ required: true, message: "备注不可为空", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.id == 0) {
        https.Writes.post("/Appliance/fixtureAdd", ruleForm).then((res) => {
          if (res.data.code == 1) {
            ElMessage.success(res.data.msg);
            dialogFormVisible.value = false;
            work_fixtureShow();
            return;
          } else {
            ElMessage.error(res.data.msg);
            return;
          }
        });
      } else {
        https.Writes.put("/Appliance/fixtureUpdate", ruleForm).then((res) => {
          if (res.data.code == 1) {
            ElMessage.success(res.data.msg);
            dialogFormVisible.value = false;
            work_fixtureShow();
            return;
          } else {
            ElMessage.error(res.data.msg);
            return;
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const open = (id: any) => {
  ElMessageBox.confirm("请问确认要删除吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.put("/Appliance/fixtureDeletee", { id: id }).then((res) => {
        if (res.data.code == 1) {
          ElMessage.success(res.data.msg);
          work_fixtureShow();
          return;
        } else {
          ElMessage.error(res.data.msg);
          return;
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
};

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的工装夹具档案！");
    return;
  }
  const ids = multipleSelection.value.map((item) => item.id);
  ElMessageBox.confirm("确认要批量删除选中的工装夹具档案吗？", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.delete("/Appliance/fixtureDeletes", {
        data: { ids },
      }).then((res) => {
        if (res.data.code == 1) {
          ElMessage.success(res.data.msg);
          work_fixtureShow();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作已取消",
      });
    });
};

//工装夹具类型下拉框
const work_fixturetypelist = ref([
  {
    id: "",
    work_fixturetypename: "",
  },
]);
const work_fixturetypeshow = () => {
  https.Reads.get("/Applicae/work_fixturetypelist").then((res) => {
    console.log(res.data);
    work_fixturetypelist.value = res.data.data;
  });
};

//所属仓库下拉框（保留用于表单）
const warehouselist = ref([
  {
    id: "",
    work_fixturetypename: "",
  },
]);
const warehouseshow = () => {
  // 这个函数可能用于其他用途，暂时保留
  https.Reads.get("/Applicae/work_fixturetypelist").then((res) => {
    console.log(res.data);
    warehouselist.value = res.data.data;
  });
};

//所属库位下拉框
const Reservoirlist = ref([
  {
    id: "",
    work_fixtureseatname: "",
  },
]);
const Reservoirshow = () => {
  https.Reads.get("/Applicae/Work_fixtureseatlist").then((res) => {
    console.log(res.data);
    Reservoirlist.value = res.data.data;
  });
};

const selectedTypeName = computed(() => {
  const target = warehouselist.value.find(
    (item) => String(item.id) === String(ruleForm.work_fixturetypeid || "")
  );
  return target?.work_fixturetypename || "未选择";
});

const selectedSeatName = computed(() => {
  const target = Reservoirlist.value.find(
    (item) => String(item.id) === String(ruleForm.work_fixtureseatid || "")
  );
  return target?.work_fixtureseatname || "未选择";
});
</script>

<style scoped>
.work-fixture-page {
  min-height: 100vh;
  background: radial-gradient(
      circle at 12% 18%,
      rgba(64, 158, 255, 0.12),
      transparent 45%
    ),
    radial-gradient(circle at 80% 0%, rgba(64, 158, 255, 0.15), transparent 40%),
    #f5f7fb;
  padding: 24px;
  box-sizing: border-box;
}

.work-fixture-page::before {
  display: none;
}

.hero-card {
  background: linear-gradient(135deg, #eef4ff, #ffffff);
  border-radius: 18px;
  padding: 20px 24px;
  border: 1px solid rgba(64, 158, 255, 0.25);
  box-shadow: 0 22px 50px rgba(64, 158, 255, 0.16);
  display: flex;
  flex-direction: column;
  gap: 12px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.hero-card::before {
  content: "";
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(
    circle,
    rgba(64, 158, 255, 0.1) 0%,
    transparent 70%
  );
  animation: pulse 8s ease-in-out infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 0.3;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.1);
  }
}

.hero-card:hover {
  box-shadow: 0 26px 60px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.hero-content {
  display: flex;
  justify-content: space-between;
  gap: 18px;
  flex-wrap: wrap;
}

.hero-title {
  display: flex;
  gap: 14px;
  align-items: flex-start;
}

.hero-icon {
  width: 56px;
  height: 56px;
  border-radius: 18px;
  background: linear-gradient(
    135deg,
    rgba(64, 158, 255, 0.2),
    rgba(64, 158, 255, 0.1)
  );
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  font-size: 30px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.hero-icon::before {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.3), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.hero-icon:hover {
  transform: rotate(5deg) scale(1.05);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
}

.hero-icon:hover::before {
  opacity: 1;
}

.hero-title h2 {
  margin: 4px 0 0;
  font-size: 22px;
  color: #1f2d3d;
}

.hero-subtitle {
  margin: 0;
  color: #7c8499;
  font-size: 13px;
}

.hero-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.hero-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(110px, 1fr));
  gap: 12px;
  min-width: 240px;
}

.meta-item {
  border-radius: 12px;
  padding: 12px 14px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(64, 158, 255, 0.18);
  transition: all 0.3s ease;
  cursor: default;
}

.meta-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.15);
  border-color: rgba(64, 158, 255, 0.3);
}

.meta-item.warning {
  border-color: rgba(230, 162, 60, 0.45);
  background: rgba(255, 248, 235, 0.95);
}

.meta-label {
  font-size: 12px;
  color: #8c8fa3;
}

.meta-item strong {
  display: block;
  margin-top: 6px;
  font-size: 24px;
  font-weight: 700;
  color: #1f2d3d;
}

.hero-breadcrumb {
  font-size: 13px;
  color: #8c8c8c;
}

.breadcrumb-card {
  border-radius: 12px;
  background: linear-gradient(
    135deg,
    rgba(255, 255, 255, 0.95),
    rgba(255, 255, 255, 0.9)
  );
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.breadcrumb-icon {
  font-size: 28px;
  color: #409eff;
}

.breadcrumb-subtitle {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.breadcrumb-heading {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(8px);
  box-shadow: 0 18px 38px rgba(52, 96, 255, 0.07);
  border: 1px solid rgba(64, 158, 255, 0.12);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 22px 48px rgba(52, 96, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2d3d;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.search-form :deep(.el-input__wrapper) {
  transition: all 0.3s ease;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.1) inset;
}

.search-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.3) inset;
}

.search-form :deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset, 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.search-form :deep(.el-select .el-input__wrapper) {
  transition: all 0.3s ease;
}

.search-form :deep(.el-select:hover .el-input__wrapper) {
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.3) inset;
}

.search-actions {
  display: flex;
  gap: 8px;
}

.search-actions .el-button {
  transition: all 0.3s ease;
  border-radius: 8px;
}

.search-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.search-actions .el-button--primary {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
}

.table-card {
  border-radius: 14px;
  background: #fff;
  box-shadow: 0 18px 38px rgba(52, 96, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.12);
  transition: all 0.3s ease;
  overflow: hidden;
}

.table-card:hover {
  box-shadow: 0 22px 48px rgba(52, 96, 255, 0.12);
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  margin-bottom: 14px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-pagination {
  margin-top: 20px;
  padding: 16px;
  background: linear-gradient(
    135deg,
    rgba(64, 158, 255, 0.03),
    rgba(103, 194, 58, 0.02)
  );
  border-radius: 12px;
  border: 1px solid rgba(64, 158, 255, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-info {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.pagination-info strong {
  color: #409eff;
  font-weight: 600;
  margin: 0 4px;
}

.pagination-text {
  white-space: nowrap;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.modern-table {
  border-radius: 8px;
  overflow: hidden;
}

.modern-table :deep(.el-table__header) {
  background: linear-gradient(
    135deg,
    rgba(64, 158, 255, 0.08),
    rgba(64, 158, 255, 0.04)
  );
}

.modern-table :deep(.el-table__header th) {
  background: transparent;
  color: #303133;
  font-weight: 600;
  border-bottom: 2px solid rgba(64, 158, 255, 0.2);
  padding: 14px 0;
}

.modern-table :deep(.el-table__body tr) {
  transition: all 0.3s ease;
}

.modern-table :deep(.el-table__body tr:hover) {
  background: linear-gradient(
    90deg,
    rgba(64, 158, 255, 0.06),
    rgba(64, 158, 255, 0.02)
  ) !important;
  transform: translateX(2px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.modern-table :deep(.el-table__body td) {
  padding: 16px 0;
  border-bottom: 1px solid rgba(64, 158, 255, 0.08);
}

.modern-table
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped) {
  background: rgba(64, 158, 255, 0.02);
}

.modern-table
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped:hover) {
  background: linear-gradient(
    90deg,
    rgba(64, 158, 255, 0.08),
    rgba(64, 158, 255, 0.04)
  ) !important;
}

.table-id {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.table-code {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  color: #303133;
}

.code-icon {
  color: #409eff;
  font-size: 16px;
}

.table-name {
  font-weight: 500;
  color: #303133;
}

.table-model {
  color: #606266;
  font-size: 13px;
}

.table-seat {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.seat-icon {
  color: #67c23a;
  font-size: 16px;
}

.table-remark {
  color: #909399;
  font-size: 13px;
}

.table-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.table-actions .el-button {
  transition: all 0.3s ease;
}

.table-actions .el-button:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.toolbar-btn-primary {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.toolbar-btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.toolbar-btn-danger {
  transition: all 0.3s ease;
}

.toolbar-btn-danger:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.code-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.fixture-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 8px 4px 20px;
  background: #f9fbff;
  border-radius: 12px;
}

.fixture-section-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 16px;
}

.fixture-section--wide {
  grid-column: span 2;
  min-width: min(100%, 640px);
}

@media (max-width: 920px) {
  .fixture-section--wide {
    grid-column: span 1;
  }
}

.fixture-section {
  background: #fff;
  border-radius: 12px;
  padding: 18px 20px 12px;
  box-shadow: 0 4px 18px rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.12);
}

.fixture-section__title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 14px;
}

.fixture-section__title .el-icon {
  color: #409eff;
}

.code-switch-label {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}

.fixture-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 4px;
}

.fixture-dialog-subtitle {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.fixture-dialog-title {
  margin: 4px 0 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.fixture-dialog-body {
  padding: 4px 6px 0;
}

.fixture-summary-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px dashed rgba(64, 158, 255, 0.4);
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.06);
  box-shadow: inset 0 0 12px rgba(64, 158, 255, 0.08);
}

.summary-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.summary-icon {
  font-size: 26px;
  color: #409eff;
}

.summary-label {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.summary-value {
  margin: 2px 0 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.summary-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.fixture-scroll {
  margin-top: 14px;
}

.fixture-layout {
  display: flex;
  gap: 18px;
  margin-top: 16px;
  align-items: flex-start;
}

.fixture-layout__form {
  flex: 1;
}

.fixture-layout__side {
  width: 340px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.fixture-side-card {
  background: #fff;
  border-radius: 14px;
  padding: 18px 20px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.15);
  position: relative;
  overflow: hidden;
}

.fixture-side-card::after {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(
    135deg,
    rgba(64, 158, 255, 0.08),
    rgba(103, 194, 58, 0.06)
  );
  opacity: 0.8;
  z-index: 0;
}

.fixture-side-card > * {
  position: relative;
  z-index: 1;
}

.preview-card__header,
.progress-card__header,
.tips-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.preview-card__header h4,
.progress-card__header h4,
.tips-card__header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.preview-descriptions {
  background: rgba(64, 158, 255, 0.06);
  border-radius: 10px;
  padding: 12px;
  margin-bottom: 12px;
}

:deep(.preview-descriptions .el-descriptions__label) {
  color: #606266;
}

.preview-chips {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.progress-card__header span {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.progress-card__text {
  margin: 10px 0;
  font-size: 13px;
  color: #606266;
}

.progress-tips {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
  padding: 6px 10px;
  border-radius: 8px;
  background: rgba(255, 153, 0, 0.08);
}

.tips-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tips-list__title {
  font-weight: 600;
  font-size: 13px;
  color: #303133;
}

.tips-list p {
  margin: 4px 0 0;
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

@media (max-width: 1280px) {
  .fixture-layout {
    flex-direction: column;
  }

  .fixture-layout__side {
    width: 100%;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .fixture-side-card {
    flex: 1;
    min-width: 260px;
  }

  .hero-content {
    flex-direction: column;
  }
}

@media (max-width: 720px) {
  .fixture-layout__side {
    flex-direction: column;
  }

  .pagination-wrapper {
    flex-direction: column;
    align-items: stretch;
  }

  .pagination-info {
    justify-content: center;
  }

  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
}

/* 添加加载动画 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

/* 优化滚动条样式 */
:deep(.el-scrollbar__bar) {
  opacity: 0.6;
}

:deep(.el-scrollbar__thumb) {
  background-color: rgba(64, 158, 255, 0.3);
  border-radius: 4px;
}

:deep(.el-scrollbar__thumb:hover) {
  background-color: rgba(64, 158, 255, 0.5);
}
</style>
